<template>
  <div>
    <h2>仪表盘</h2>
    <el-row :gutter="20">
      <el-col :span="6"><el-card>用户总数：{{ userCount }}</el-card></el-col>
      <el-col :span="6"><el-card>商品总数：{{ productCount }}</el-card></el-col>
      <el-col :span="6"><el-card>订单总数：{{ orderCount }}</el-card></el-col>
      <el-col :span="6"><el-card>分类总数：{{ categoryCount }}</el-card></el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getUserList } from '../api/user'
import { getProductList } from '../api/product'
import { getAdminOrderList } from '../api/order'
import { getCategoryTree } from '../api/category'

const userCount = ref('--')
const productCount = ref('--')
const orderCount = ref('--')
const categoryCount = ref('--')

onMounted(async () => {
  // 用户总数
  try {
    const userRes = await getUserList({ page: 1, pageSize: 10000 })
    if (Array.isArray(userRes?.data)) {
      userCount.value = userRes.data.length
    } else if (Array.isArray(userRes?.data?.list)) {
      userCount.value = userRes.data.list.length
    } else if (typeof userRes?.data?.total === 'number') {
      userCount.value = userRes.data.total
    } else {
      userCount.value = 0
    }
  } catch { userCount.value = 0 }

  // 商品总数
  try {
    const productRes = await getProductList({ page: 1, pageSize: 10000 })
    if (Array.isArray(productRes?.data)) {
      productCount.value = productRes.data.length
    } else if (Array.isArray(productRes?.data?.list)) {
      productCount.value = productRes.data.list.length
    } else if (typeof productRes?.data?.total === 'number') {
      productCount.value = productRes.data.total
    } else {
      productCount.value = 0
    }
  } catch { productCount.value = 0 }

  // 订单总数
  try {
    const orderRes = await getAdminOrderList({ page: 1, pageSize: 10000 })
    if (Array.isArray(orderRes?.data)) {
      orderCount.value = orderRes.data.length
    } else if (Array.isArray(orderRes?.data?.list)) {
      orderCount.value = orderRes.data.list.length
    } else if (typeof orderRes?.data?.total === 'number') {
      orderCount.value = orderRes.data.total
    } else {
      orderCount.value = 0
    }
  } catch { orderCount.value = 0 }

  // 分类总数
  try {
    const categoryRes = await getCategoryTree()
    const countCategories = (arr) => arr.reduce((sum, item) => sum + 1 + (item.children ? countCategories(item.children) : 0), 0)
    categoryCount.value = Array.isArray(categoryRes?.data) ? countCategories(categoryRes.data) : 0
  } catch { categoryCount.value = 0 }
})
</script>